package niu.toy.spring.mvc.impl;


import niu.toy.spring.mvc.HandlerMethodParameter;
import niu.toy.spring.mvc.ModelAndViewContainer;
import niu.toy.spring.mvc.NativeWebRequest;
import niu.toy.spring.mvc.HandlerReturnValue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public class HandlerReturnValueComposite implements HandlerReturnValue {

    private static final Logger logger = LoggerFactory.getLogger(HandlerReturnValueComposite.class);
    private final List<HandlerReturnValue> returnValueHandlers = new ArrayList<>();


    @Override
    public boolean supportsReturnType(HandlerMethodParameter returnType) {
        return getReturnValueHandler(returnType) != null;
    }

    
    private HandlerReturnValue getReturnValueHandler(HandlerMethodParameter returnType) {
        for (HandlerReturnValue handler : this.returnValueHandlers) {
            if (handler.supportsReturnType(returnType)) {
                return handler;
            }
        }
        return null;
    }

    @Override
    public void handleReturnValue( Object returnValue, HandlerMethodParameter returnType,
                                  ModelAndViewContainer mavContainer , NativeWebRequest webRequest) throws Exception {

        HandlerReturnValue handler = getReturnValueHandler(returnType);
        if (handler == null) {
            throw new IllegalArgumentException("Unknown return value type: " + returnType.getParameterType().getName());
        }
        handler.handleReturnValue(returnValue, returnType, mavContainer, webRequest);
    }

    public HandlerReturnValueComposite addHandler(HandlerReturnValue handler) {
        this.returnValueHandlers.add(handler);
        return this;
    }

}
